/*
 * RFM12_protocol.h
 *
 *  Created on: 27.07.2011
 *      Author: Sebastian Bauer
 */

#ifndef RFM12_PROTOCOL_H_
#define RFM12_PROTOCOL_H_

#include <stdint.h>
#include <boolean.h>


/* packet type: 0 = command, 1 = data */
#define RFM12_PACKET_CMD 	0x00
#define RFM12_PACKET_DATA 	0x80
//TODO: protocol bytes

/* Packet Command Types */
#define RFM12_PACKET_CMD_BEGIN		(0x00 << 3)
#define RFM12_PACKET_CMD_SUCCESS	(0x01 << 3)
#define RFM12_PACKET_CMD_ERROR		(0x02 << 3)
#define RFM12_PACKET_CMD_END		(0x03 << 3)

/* States */
#define RFM12_PROT_STATE_NONE				0x00
#define RFM12_PROT_STATE_TRANSMITTING		0x01
#define RFM12_PROT_STATE_RECEIVING			0x02
#define RFM12_PROT_STATE_WAIT_FOR_ANSWER	0x03
#define RFM12_PROT_STATE_TRANSMIT_FINISHED	0x04
#define RFM12_PROT_STATE_RECEIVE_FINISHED	0x05


uint8_t RFM12_prot_state;
uint8_t RFM12_prot_last_error;
uint8_t RFM12_prot_address;
uint8_t RFM12_prot_statusRegister; // 0 = ready, 1 = not ready

/**
 * Sends data using the implemented protocol
 *
 * Parameters:
 * data: pointer to data which should be transmitted
 * length: length of the data in bytes
 *
 * Returns:
 * true if all went fine, false if an error occurs. In that case
 * use RFM12_prot_getLastError_send() to get the cause.
 */
boolean extern RFM12_tx_Data(uint8_t* data, uint16_t length);

//TODO: rx data

/**
 * Returns the last sending error. It resets after every successful transmit.
 */
int8_t inline static RFM12_prot_getLastError_send(void) {
	return RFM12_prot_last_error;
}

void inline static RFM12_prot_setAddress(uint8_t address) {
	RFM12_prot_address = (address << 5) & 0x9F; /* shift to correct position and de-mask all other bits */
}

void inline static RFM12_prot_init(void) {
	RFM12_prot_state = RFM12_PROT_STATE_NONE;
	RFM12_prot_last_error = 0;
	RFM12_prot_address = 0;
	RFM12_prot_statusRegister = 0;
}

/* Error Values */
#define RFM12_PACKET_SEND_SUCCESS			0x00 /* all went fine */
#define RFM12_PACKET_SEND_ERROR				0x01 /* an undefined error occurred */
#define RFM12_PACKET_SEND_TIMEOUT			0x02 /* timeout (recipient didn't answer) */
#define RFM12_PACKET_SEND_ALREADY_RECEIVING	0x03 /* already receiving, try again later */


#endif /* RFM12_PROTOCOL_H_ */
